use super::*;

/// A [Script Table](https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#script-table-and-language-system-record).
#[derive(Clone, Copy, Debug)]
pub struct Script<'a> {
	/// Script tag.
	pub tag: Tag,
	/// Default language.
	pub default_language: Option<LangSys<'a>>,
	/// List of supported languages, excluding the default one. Listed alphabetically.
	pub languages: LangSysList<'a>,
}

impl<'a> RecordListItem<'a> for Script<'a> {
	fn parse(tag: Tag, data: &'a [u8]) -> Option<Self> {
		let mut s = Stream::new(data);
		let mut default_language = None;
		if let Some(offset) = s.read::<Option<Offset16>>()? {
			default_language = LangSys::parse(Tag::from_bytes(b"dflt"), data.get(offset.to_usize()..)?);
		}
		let mut languages = RecordList::parse(s.tail()?)?;
		// Offsets are relative to this table.
		languages.data = data;
		Some(Self {
			tag,
			default_language,
			languages,
		})
	}
}

/// A [Language System Table](https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#language-system-table).
#[derive(Clone, Copy, Debug)]
pub struct LangSys<'a> {
	/// Language tag.
	pub tag: Tag,
	/// Index of a feature required for this language system.
	pub required_feature: Option<FeatureIndex>,
	/// Array of indices into the FeatureList, in arbitrary order.
	pub feature_indices: LazyArray16<'a, FeatureIndex>,
}

impl<'a> RecordListItem<'a> for LangSys<'a> {
	fn parse(tag: Tag, data: &'a [u8]) -> Option<Self> {
		let mut s = Stream::new(data);
		let _lookup_order = s.read::<Offset16>()?; // Unsupported.
		Some(Self {
			tag,
			required_feature: match s.read::<FeatureIndex>()? {
				0xFFFF => None,
				v => Some(v),
			},
			feature_indices: s.parse_array16()?,
		})
	}
}
